package com.zjweu.hkg.Servies.impl;
import com.zjweu.hkg.DAO.ArticleDAO;
import com.zjweu.hkg.DAO.UserDAO;
import com.zjweu.hkg.DTO.ArticleViewHistoryDTO;
import com.zjweu.hkg.DTO.ArticleWithTagsDTO;
import com.zjweu.hkg.POJO.*;
import com.zjweu.hkg.Servies.ArticleService;
import com.zjweu.hkg.Servies.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleDAO articleDAO;
    @Autowired
    FileService fileService;
    @Autowired
    UserDAO userDAO;
    public Article createArticleByRequestData(Map<String, Object> requestData) {
        Article article = new Article();

        // 从 requestData 中获取数据并设置到 Article 对象中
        if (requestData.containsKey("articleId")) {
            article.setArticleId((int) requestData.get("articleId"));
        }
        if (requestData.containsKey("articleTitle")) {
            article.setArticleTitle((String) requestData.get("articleTitle"));
        }
        if (requestData.containsKey("articleContent")) {
            article.setArticleContent((String) requestData.get("articleContent"));
        }
        if (requestData.containsKey("authorUID")) {
            article.setAuthorUID((int) requestData.get("authorUID"));
        }
        if (requestData.containsKey("createDate")) {
            article.setCreateDate((Date) requestData.get("createDate"));
        }
        if (requestData.containsKey("updateDate")) {
            article.setUpdateDate((Date) requestData.get("updateDate"));
        }
        if(requestData.containsKey("readTime")){
            article.setReadTime((int) requestData.get("readTime"));
        }
        if(requestData.containsKey("articleUUID")){
            article.setArticleUUID((String) requestData.get("articleUUID"));
        }
        if(requestData.containsKey("permission")){
            article.setPermission((int) requestData.get("permission"));
        }
    if(requestData.containsKey("status")){
            article.setStatus((int) requestData.get("status"));
        }
        return article;
    }
    public List createTagByRequestData(Map<String, Object> requestData){
        if(requestData.containsKey("tag")){
            return (ArrayList) requestData.get("tag");
        }
        return null;
    }
    @Override
    public Result<Integer> addArticle(Map<String, Object> requestData) {

        //从requestData中创建文章和标签的对象
        Article article=createArticleByRequestData(requestData);
        articleDAO.insertArticle(article);
        List tags=createTagByRequestData(requestData);
        // 对每个标签进行操作
        for (Object tagContent : tags) {
            // 创建标签对象
            Tag tag = new Tag();
            tag.setTagContent((String) tagContent);

            // 判断标签是否存在，如果不存在则插入
            articleDAO.insertTagIfNotExist(tag);

            // 获取标签ID
            int tagId = articleDAO.getTagIdByContent((String) tagContent);

            // 插入文章与标签的关联
            ArticleTags articleTags = new ArticleTags();
            articleTags.setArticleId(article.getArticleId());
            articleTags.setTagId(tagId);
            articleDAO.insertArticleTag(articleTags);
        }

        return Result.success(article.getArticleId());
    }

    @Override
    public ResponseEntity<String> uploadArticleImage(MultipartFile file, String userName,String articleUUID) {
        String newFileName=fileService.changeFileNameWithPath(file.getOriginalFilename(),userName,"article/"+articleUUID);
        ArticleFiles articleFiles=new ArticleFiles(newFileName,articleUUID);
        articleDAO.insertArticleFiles(articleFiles);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", file.getResource());
        body.add("fileName", newFileName);
        body.add("bucketName", "hkg");
        // 返回响应内容
        return fileService.upload(file,newFileName,body);
    }

    @Override
    public List<ArticleWithTagsDTO> getAllArticleWithTags() {
        List<ArticleWithTagsDTO> articleWithTagsDTOS=new ArrayList<>();
        List<Article> articleList=articleDAO.findAllArticle();
        for (int i = 0; i < articleList.size(); i++) {
            Article article=articleList.get(i);

            User author=userDAO.getUserById(article.getAuthorUID());
            List<ArticleTags> articleTags=articleDAO.findArticleTagsByArticleId(article.getArticleId());
            List<String> tagName=new ArrayList<>();
            for (int j = 0; j < articleTags.size(); j++) {
                ArticleTags articleTags1 = articleTags.get(j);
                Tag tag = articleDAO.findTagsByTagId(articleTags1.getTagId());
                tagName.add(tag.getTagContent());
            }
            ArticleWithTagsDTO articleWithTagsDTO=new ArticleWithTagsDTO(article,tagName,author);
            articleWithTagsDTOS.add(articleWithTagsDTO);
        }
        return articleWithTagsDTOS;
    }

    @Override
    public ArticleWithTagsDTO getArticleWithTagsByArticleId(int articleId,int uid) {
        Article article=articleDAO.findArticleByArticleId(articleId);
        if(article==null){
            return null;
        }
        User author=userDAO.getUserById(article.getAuthorUID());
        List<String> tagName=new ArrayList<>();
        List<ArticleTags> articleTags=articleDAO.findArticleTagsByArticleId(article.getArticleId());
        for (int j = 0; j < articleTags.size(); j++) {
            ArticleTags articleTags1 = articleTags.get(j);
            Tag tag = articleDAO.findTagsByTagId(articleTags1.getTagId());
            tagName.add(tag.getTagContent());
        }
        ArticleWithTagsDTO articleWithTagsDTO=new ArticleWithTagsDTO(article,tagName,author);

        //增加阅读量
        Date now=new Date();
        System.out.println("现在是:"+now);
        ArticleViewHistory articleViewHistory=articleDAO.findLastViewTimeByUserIdAndArticleId(uid,articleId);
        Date lastViewTime;
        if(articleViewHistory==null){
             lastViewTime=new Date(1970,1,1,0,0,0);
        }else{
            lastViewTime=articleViewHistory.getCreateTime();
        }


        System.out.println("上次浏览时间是:"+lastViewTime);
        if(isTimeDifferenceMoreThan4Hours(lastViewTime,now)){
            //增加阅读量
            addReadTimeByArticleId(articleWithTagsDTO);
            System.out.println("增加阅读量成功");
        }else{
            System.out.println("时间差小于4小时，不增加阅读量");
        }




        return articleWithTagsDTO;
    }

    @Override
    public ArticleWithTagsDTO getArticleWithTagsByArticleId(int articleId) {
        Article article=articleDAO.findArticleByArticleId(articleId);
        if(article==null||article.getStatus()==1){
//            return new ArticleWithTagsDTO(-1,"【已删除的文章】",null,-1,null,null,null,-1,null,null, ConstUtil.ARTICLE_PERMISSION_PUBLIC,ConstUtil.ARTICLE_STATUS_DELETED);
                return new ArticleWithTagsDTO(Article.setArticleDelete(article),null,null);

        }
        System.out.println(articleId);
        User author=userDAO.getUserById(article.getAuthorUID());
        List<String> tagName=new ArrayList<>();
        List<ArticleTags> articleTags=articleDAO.findArticleTagsByArticleId(article.getArticleId());
        for (int j = 0; j < articleTags.size(); j++) {
            ArticleTags articleTags1 = articleTags.get(j);
            Tag tag = articleDAO.findTagsByTagId(articleTags1.getTagId());
            tagName.add(tag.getTagContent());
        }
        ArticleWithTagsDTO articleWithTagsDTO=new ArticleWithTagsDTO(article,tagName,author);
        return articleWithTagsDTO;
    }

    @Override
    public Result<String> addReadTimeByArticleId(ArticleWithTagsDTO articleWithTagsDTO) {
        int articleId=articleWithTagsDTO.getArticle().getArticleId();
        int newReadTime=articleWithTagsDTO.getArticle().getReadTime()+1;
        int result=articleDAO.addReadTimeByArticleId(articleId,newReadTime);
        if(result==1){
            return Result.success();
        }
        return   Result.error("读取文章浏览次数失败！");
    }

    @Override
    public int addArticleViewHistory(int articleId, int userId) {
        return articleDAO.addArticleViewHistory(articleId,userId);
    }

    @Override
    public List<ArticleWithTagsDTO> getAllArticleWithTagsByUserId(int userId) {
        List<ArticleWithTagsDTO> articleWithTagsDTOS=new ArrayList<>();
        List<Article> articleList=articleDAO.findArticleByUserId(userId);
        for (int i = 0; i < articleList.size(); i++) {
            Article article=articleList.get(i);
            System.out.println("author"+article.getAuthorUID());
            User author=userDAO.getUserById(article.getAuthorUID());
            List<ArticleTags> articleTags=articleDAO.findArticleTagsByArticleId(article.getArticleId());
            List<String> tagName=new ArrayList<>();
            for (int j = 0; j < articleTags.size(); j++) {
                ArticleTags articleTags1 = articleTags.get(j);
                Tag tag = articleDAO.findTagsByTagId(articleTags1.getTagId());
                tagName.add(tag.getTagContent());
            }
            ArticleWithTagsDTO articleWithTagsDTO=new ArticleWithTagsDTO(article,tagName,author);
            articleWithTagsDTOS.add(articleWithTagsDTO);
        }
        return articleWithTagsDTOS;
    }

    @Override
    public Result<Integer> updateArticleWithTagsByArticleId(ArticleWithTagsDTO articleWithTagsDTO) {
        Article article=ArticleWithTagsDTO.convert2Article(articleWithTagsDTO);
        articleDAO.updateArticle(article);
        articleDAO.deleteArticleTagsByArticleId(article.getArticleId());
        System.out.println("标签是："+articleWithTagsDTO.getTagNames().size());
        for (int i = 0; i < articleWithTagsDTO.getTagNames().size(); i++) {

            Tag tag=new Tag(articleWithTagsDTO.getTagNames().get(i));
            articleDAO.insertTagIfNotExist(tag);
            int tagId=articleDAO.getTagIdByContent(articleWithTagsDTO.getTagNames().get(i));
            ArticleTags articleTags=new ArticleTags(article.getArticleId(),tagId);
            articleDAO.insertArticleTag(articleTags);
        }
        return Result.success(article.getArticleId());
    }

    @Override
    public Result<String> deleteArticleByArticleId(int articleId) {
        if(articleDAO.deleteArticleByArticleId(articleId)==1){
            articleDAO.deleteArticleTagsByArticleId(articleId);
            return Result.success("删除成功");
        }else{
            return Result.error("删除失败");
        }

    }

    /**
     * 我是傻逼，取名字和返回值不一样
     * @param userId
     * @return
     */
    @Override
    public List<ArticleViewHistoryDTO> findArticleViewHistoryByUserId(int userId) {
        List<ArticleViewHistoryDTO> articleViewHistoryDTOS=new ArrayList<>();
        List<ArticleViewHistory> articleViewHistoryList=articleDAO.findArticleViewHistoryByUserId(userId);
        for (int i = 0; i < articleViewHistoryList.size(); i++) {
            ArticleViewHistory articleViewHistory=articleViewHistoryList.get(i);
            ArticleWithTagsDTO articleWithTagsDTO=getArticleWithTagsByArticleId(articleViewHistory.getArticleId());
            ArticleViewHistoryDTO articleViewHistoryDTO=new ArticleViewHistoryDTO(
                    articleViewHistory.getArticleId(),
                    articleWithTagsDTO.getArticle().getArticleTitle(),
                    articleViewHistory.getCreateTime()
            );
            articleViewHistoryDTOS.add(articleViewHistoryDTO);
        }
        return articleViewHistoryDTOS;
    }

    @Override
    public List<ArticleViewHistory> getArticleViewHistoryByUserId(int userId) {
        return articleDAO.findArticleViewHistoryByUserId(userId);
    }

    @Override
    public List<ArticleTags> findArticleTagsByArticleId(int articleId) {
        return articleDAO.findArticleTagsByArticleId(articleId);
    }

    @Override
    public Tag findTagsByTagId(int tagId) {
        return articleDAO.findTagsByTagId(tagId);
    }

    @Override
    public List<ArticleWithTagsDTO> getArticlesByTags(List<String> tags) {
        // 对传入的标签进行模糊查询处理
        for (int i = 0; i < tags.size(); i++) {
            tags.set(i, "%" + tags.get(i) + "%");
        }
//        System.out.println("推荐的文章是："+articleDAO.simpleTest(tags));
        return articleDAO.getArticlesByTags(tags);
    }

    @Override
    public List<ArticleWithTagsDTO> likeSearchArticleByName(String articleTitle) {
        return articleDAO.likeSearchArticleByName(articleTitle);
    }

    @Override
    public List<ArticleWithTagsDTO> getFollowedArticles(int userId) {

        List<ArticleWithTagsDTO> articleWithTagsDTOS=articleDAO.getFollowedArticles(userId);
        for (int i = 0; i < articleWithTagsDTOS.size(); i++) {
            ArticleWithTagsDTO articleWithTagsDTO = articleWithTagsDTOS.get(i);
            //添加用户信息
            User author = userDAO.getUserById(articleWithTagsDTO.getArticle().getAuthorUID());
            articleWithTagsDTO.setAuthor(author);

        }
        if(articleWithTagsDTOS!=null){
            return (articleWithTagsDTOS);
        }
        return null;
    }

    /**
     * 再取一个相近的名字写代码得了
     *
     * @return
     */

    public static boolean isTimeDifferenceMoreThan4Hours(Date date1, Date date2) {
        // 获取两个日期的时间戳（毫秒数）
        long time1 = date1.getTime();
        long time2 = date2.getTime();

        // 计算时间差的绝对值
        long difference = Math.abs(time1 - time2);

        // 24小时的毫秒数
        long twentyFourHoursInMillis = 4 * 60 * 60 * 1000L;

        // 判断差值是否超过24小时
        return difference > twentyFourHoursInMillis;
    }
}
